<?php

namespace App\Http\Controllers\Admin;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use	App\Brands;
use App\Models;
use App\Items;
use	Image;


class BrandController extends Controller
{
	/**
	 * 设置分页大小
	 */
	public $pageSize = null;
	
	public function __construct()
	{
		$this->pageSize	 = CS('admin_page_size')!=''?CS('admin_page_size'):20;
	}
	

	/**
	 * 品牌列表
	 */
	public function index(Request $req)
	{
		//权限验证
		if(!in_array('brand_list',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}

		$title 		= trans('admin.brand_list');
		$brand_id	= isset($req->brand_id)?trim($req->brand_id):'';
		$is_hot		= isset($req->is_hot)?trim($req->is_hot):'';
		$brand_name	= isset($req->brand_name)?htmlspecialchars((trim($req->brand_name))):'';
		
		$where 	= [];
		
		if($brand_id !== '')
		{
			$where   =  array_merge($where, ['brand_id' => $brand_id]);
		}
		
		if($is_hot !== '')
		{
			$where   =  array_merge($where, ['is_hot' => $is_hot]);
		}
		
		
		if($brand_name !== '')
		{
			$data	= Brands::orderBy('brand_id','desc')
				->where($where)
				->where('brand_name','like','%'.$brand_name.'%')
				->paginate($this -> pageSize);	
		}
		else
		{
			$data	= Brands::orderBy('brand_id','desc')
				->where($where)
				->paginate($this -> pageSize);	
		}
		
		return view('admin.brand.brand_list',['title'=> $title,
			'data'			=>	$data,
			'brand_id'		=>	$brand_id,
			'brand_name'	=>	$brand_name,
			'is_hot'		=>  $is_hot,
		]);
	}


	/**
	 * 添加品牌
	 */
	public	function	brandAdd(Request $req)
	{
		//权限验证
		if(!in_array('brand_add',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
		
		if($req->isMethod('get'))
		{
			$title 	= trans('admin.brand_add');				
			return view('admin.brand.brand_add',['title'=>$title,

			]);	
		}
		elseif($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'brand_name'	=> 'required|max:100',
	            'is_hot'  		=> 'in:0,1',
	            'sort_order'	=> 'integer',
	           	'telephone'		=> 'max:100',
	           	'area'			=> 'max:50',
	            'address'		=> 'max:100',
	            'desc'			=> 'max:1000',
	        ];
			
	        $message = [
	            'brand_name.required'	=> '品牌名称是必须的',
				'brand_name.max' 		=> '品牌名称长度不能大于100',
				'address.max' 	 		=> '详细地址长度不能大于100',
				'sort_order.integer'	=> '排序为数字',
				'area.max' 	 			=> '地区长度不能大于50',
				'telephone.max' 	 	=> '联系电话长度不能大于100',
				'desc.max' 	 			=> '品牌信息长度不能大于100',
	
	        ];
	
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			$brand_id = Brands::insertGetId(['brand_name' => trim($req->brand_name),
				'brand_name'	=> trim($req->brand_name),
				'area' 			=> trim($req->area),
				'desc' 			=> trim($req->desc),
				'is_hot'		=> trim($req->is_hot),
				'is_hot'		=> trim($req->is_hot),
				'sort_order'	=> trim($req->sort_order),
				'website'		=> 'http://'.trim($req->website),
				'address'		=> trim($req->address),
				'telephone'		=> trim($req->telephone),
			]);
			
			//logo处理
			if(isset($input['brand_logo']))
			{				
				$path = 'uploads/brands/'.date('Y/m/');
				if(!is_dir($path))
				{
					mkdir($path,0777,true);
				}
				
				$img_ori	= Image::make($input['brand_logo'])->resize(120,50);
		        $_oriPath  	= $path.rand(1111,9999).'_'.strRand(4).'.jpg';
				$img_ori->save($_oriPath);
				
				Brands::where('brand_id',$brand_id)
				->update(['brand_logo' => $_oriPath]);				
			}
			
			//型号处理
			if(isset($input['model']) && $input['model'] !== '')
			{
				$models = explode("\n", $input['model']);
				foreach($models as $m)
				{
					Models::insert(['brand_id'=> $brand_id,
						'model'		=> trim($m),
						'is_show'	=> 0,
					]);
				}
			}
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.add_succ'),
				'url' => url('admin/brand')
			]);
							
		}

	}



	/**
	 * 	品牌型号修改
	 */
	public	function	brandUpdate(Request $req,$id)
	{
		//权限验证
		if(!in_array('brand_edit',session('access')))
		{
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'fail',
				'info' => trans('admin.access_fail'),
				'url' => url('admin/info')
			]);
		}
			
		if(Brands::where('brand_id',$id)->count() < 1)
		{
			return redirect('admin/brand');
		}

		$brand	= Brands::where('brand_id',$id)->first();

		if($req->isMethod('get'))
		{
			$title 	= trans('admin.brand_update');				
			$models	= Models::where('brand_id',$id)->get();
			return view('admin.brand.brand_update',['title'=>$title,
				'brand'		=>		$brand ,		
				'models'	=>		$models,
			]);
		}
		else if($req->isMethod('post'))
		{
			$input = Input::except('MAX_FILE_SIZE','_token');
			//验证字段
	        $rule = [
	            'brand_name'	=> 'required|max:100',
	            'is_hot'  		=> 'in:0,1',
	            'sort_order'	=> 'integer',
	           	'telephone'		=> 'max:100',
	           	'area'			=> 'max:50',
	            'address'		=> 'max:100',
	            'desc'			=> 'max:1000',
	        ];
			
	        $message = [
	            'brand_name.required'	=> '品牌名称是必须的',
				'brand_name.max' 		=> '企业名称长度不能大于100',
				'address.max' 	 		=> '详细地址长度不能大于100',
				'sort_order.integer'	=> '排序为数字',
				'area.max' 	 			=> '地区长度不能大于50',
				'telephone.max' 	 	=> '联系电话长度不能大于100',
				'desc.max' 	 			=> '品牌信息长度不能大于100',
	
	        ];
	
	        $validate = Validator::make($input,$rule,$message);
	        if($validate->fails())
	        {
	            return back()-> withErrors($validate)->withInput($req->all());
	        }
			
			Brands::where('brand_id',$id)
			->update(['brand_name' => trim($req->brand_name),
				'brand_name'	=> trim($req->brand_name),
				'area' 			=> trim($req->area),
				'desc' 			=> trim($req->desc),
				'is_hot'		=> trim($req->is_hot),
				'is_hot'		=> trim($req->is_hot),
				'sort_order'	=> trim($req->sort_order),
				'website'		=> 'http://'.getUrl(trim($req->website)),
				'address'		=> trim($req->address),
				'telephone'		=> trim($req->telephone),
			]);
			
			//logo处理
			if(isset($input['brand_logo']))
			{
				if($brand -> brand_logo != '')
				{
					unlink(public_path($brand -> brand_logo));
				}
				
								
				$path = 'uploads/brands/'.date('Y/m/');
				if(!is_dir($path))
				{
					mkdir($path,0777,true);
				}
				
				$img_ori	= Image::make($input['brand_logo'])->resize(120,50);
		        $_oriPath  	= $path.rand(1111,9999).'_'.strRand(4).'.jpg';
				$img_ori->save($_oriPath);
				
				Brands::where('brand_id',$id)
				->update(['brand_logo' => $_oriPath]);				
			}
			
			//型号处理
			if(isset($input['model']) && $input['model'] !== '')
			{
				$models = explode("\n", $input['model']);
				foreach($models as $m)
				{
					Models::insert(['brand_id'=> $id,
						'model'		=> trim($m),
						'is_show'	=> 0,
					]);
				}
			}
			
			return redirect()->action('Admin\IndexController@tips',['sec'=>'3','act'=>'succ',
				'info' => trans('admin.update_succ'),
				'url' => url('admin/brand')
			]);			
		}	
	}

	



	/**
	 * 修改型号
	 */
	public function	modelUpdate(Request $req)
	{
		if(Models::where('model_id',$req->model_id)->count() < 1)
		{
			return ['error'=>1,'message'=>'failed','content'=>'该型号不存在！'];
		}
		else
		{
			if(strlen(trim($req->model)) !== '')
			{
				if(strlen(trim($req->model)) > 60)
				{
					return ['error'=>1,'message'=>'failed','content'=>'型号不能超过20个字符！'];
				}
				
				Models::where('model_id',$req->model_id)
	            ->update(['model' => trim($req->model)]);	
				return ['error'=>0,'message'=>'success'];
			}
		}
	}

	/**
	 * 查询品牌下的型号
	 */
	public function getModelByBrand(Request $req)
	{
		$brand_id = $req->brand_id;
		$data	  = Models::where('brand_id',$brand_id)->get();
		return $data; 
	}
	
	
	

	/**
	 *	品牌删除接口 
	 */
	public function	del(Request $req)
	{
		//权限验证
		if(!in_array('brand_del',session('access')))
		{
			return ['error'=>1,
				'message'=>'fail',
				'content'=>'没有该操作的权限!',
			];
		}
		
		$id = isset($req->id)?intval($req->id):'0';
		if(Brands::where('brand_id',$id)->count() > 0)
		{
			//获取品牌信息
			$brand = Brands::where('brand_id',$id)->first();
			//获取所有型号
			$models = Models::where('brand_id',$id)->get();
			//使用该品牌的商品条数
			$count = Items::where('brand_id',$id)->count();
			//商品id
			$ids = '';
			foreach( Items::where('brand_id',$id)->get() as $k => $v)
			{
				$ids .= ' '.$v->item_id.',';
			}
			$ids = substr($ids,0,-1);
			
			if($count > 0)
			{
				return ['error'=>1,
					'message'=>'fail',
					'content'=>'已有编号为'.$ids.' 等'.$count.'个商品使用该品牌，无法删除!',
				];
			}
			else
			{
				//删除所有型号
				if(!$models->isEmpty())
				{
					Models::where('brand_id',$id)->delete();
				}
				
				//删除品牌logo
				if($brand -> brand_logo != '')
				{
					unlink(public_path($brand -> brand_logo));
				}
				
				//删除品牌
				Brands::where('brand_id',$id)->delete();
				
				return ['error'=>0,
					'message'=>'success',
					'content'=>'删除成功!',
				];		
			}

		}	
	}





	/**
	 *	品牌批量操作 
	 */
	public function brandHandle(Request $req)
	{
		//批量设为推荐
		if($req->act == 'hot')
		{
			$in = array_flatten($req->items);
			Brands::whereIn('brand_id',$in)
            ->update(['is_hot' => 0]);
			return ['error'=>0,'message'=>'success'];
		}
		//批量取消推荐
		if($req->act == 'unhot')
		{
			$in = array_flatten($req->items);
			Brands::whereIn('brand_id',$in)
            ->update(['is_hot' => 1]);
			return ['error'=>0,'message'=>'success'];
		}
	}
	
	




















}
